package atom.core3.hibernate.dao.impl;
/**
 * Title: 获取数据库序列的dao
 * Description:
 * Copyright: Copyright (c) 2010
 * Company: 
 * @author 赵明才
 * @version 1.0
 */

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import atom.core0.util.DateUtil;
import atom.core0.util.StringUtil;


public class OracleSequenceDao extends BaseHibernateDao  {

	protected final Logger logger = Logger.getLogger(getClass());
	protected Class getEntityClass()
	{
		return null;
	}
	public Long nextVal(String sequence) {
		String sql = "SELECT " + sequence + ".NEXTVAL FROM DUAL";
		Long value = (long)0;
		try
		{
			value = ((BigDecimal)this.getUniqueResultBySql(sql)).longValue();
		}
		catch(Exception e)
		{
			logger.info("序列["+sequence+"]不存在,创建序列");
			createSeq(sequence);
			value = ((BigDecimal)this.getUniqueResultBySql(sql)).longValue();
		}
		return value;

	}
	public List nextBatchVal(String sequence,int count) {
		String sql = "SELECT " + sequence + ".NEXTVAL FROM DUAL CONNECT BY LEVEL<="+count;
		
		List list;
		try
		{
			list = this.getListBySql(sql);
			
		}
		catch(Exception e)
		{
			logger.info("序列["+sequence+"]不存在,创建序列");
			createSeq(sequence);
			list = this.getListBySql(sql);
		}
		return list;

	}	
	public String nextVal(String sequence,int formatLen) {
		//String sql = "SELECT " + sequence + ".NEXTVAL FROM DUAL";
		//Long value = ((BigDecimal)this.getUniqueResultBySql(sql)).longValue();
		Long value = nextVal(sequence);
		
		String formatStr = "%0"+formatLen+"d";//"%08d"
		String sRet = String.format(formatStr, value);
		if (sRet.length()>formatLen)
			sRet = sRet.substring(sRet.length()-formatLen);	
		return sRet;
	}
	public String nextValAndDate(String sequence,int formatLen) {
		//String sql = "SELECT " + sequence + ".NEXTVAL FROM DUAL";
		//Long value = ((BigDecimal)this.getUniqueResultBySql(sql)).longValue();
		Long value = nextVal(sequence);
		String formatStr = "%0"+formatLen+"d";//"%08d"
		String sRet = String.format(formatStr, value);
		if (sRet.length()>formatLen)
			sRet = sRet.substring(sRet.length()-formatLen);
		String date = DateUtil.getDateStr(new Date(),false);

		return date+sRet;
	}
	public boolean existSeq(String sequence)
	{
		String s = sequence.toUpperCase();
		String sql = "SELECT sequence_name FROM user_sequences where sequence_name='"+s+"'";
		String sName = ((String)this.getUniqueResultBySql(sql));
		if (StringUtil.isEmpty(sName))
			return false;
		return true;
		
	}
	public void createSeq(String sequence)
	{
		String sql = "create sequence "+sequence+" minvalue 1 maxvalue 999999999999 start with 1 increment by 1 cache 20";
		this.executeSql(sql);
	}
	
}
